package com.modules.service.sys.impl;


import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.common.constant.CommonConstant;
import com.common.vo.Result;
import com.modules.dao.sys.MenuDao;
import com.modules.dto.sys.req.MenuEntityReq;
import com.modules.dto.sys.resp.MenuEntityResp;
import com.modules.dto.sys.resp.RoleDtoResp;
import com.modules.dto.sys.resp.TreeResp;
import com.modules.entity.sys.MenuEntity;
import com.modules.entity.sys.RoleMenuEntity;
import com.modules.service.sys.MenuService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;


/**
 * service菜单
 * @author yyq
 *
 */
@Service
//@Transactional(rollbackFor = Exception.class)(readOnly = true) //全局事务（xml 如果配置了其他事务这里可以不用了）
public class MenuServiceImpl implements MenuService{

	@Resource
	private MenuDao dao;

	
    /**
     * 分页查询
     * @param
     * @return
     */
    public Result<?> select(Page<MenuEntity> page, MenuEntity menu) {
        IPage<MenuEntity> iPage = dao.selectPage(page, Wrappers.lambdaQuery());
        return Result.page(iPage.getRecords(), iPage.getTotal());
    }
    
	/**
	 * 获取树形表格
	 * @param m
	 * @return
	 */
	public Result<?> selecTreeTable(MenuEntity m) {
		m.setDelFlag(CommonConstant.ZERO);
		List<MenuEntityResp> list = dao.selectTreeAll(m);
		if(StrUtil.isNotBlank(m.getMname())) {
			List<MenuEntityResp> resList = CollUtil.newArrayList();
			for(MenuEntityResp menu : list) {
				if(menu.getMname().indexOf(m.getMname()) != -1) {
					resList.add(menu);
					selectTreeTableChildrend(resList, list, menu.getMid());
				}
			}
			return Result.page(resList, Long.valueOf(resList.size()));
		}
		return Result.page(list, Long.valueOf(list.size()));
	}

	public void selectTreeTableChildrend(List<MenuEntityResp> resList, List<MenuEntityResp> list, Integer mid) {
		for(MenuEntityResp menu : list) {
			if(menu.getParentId().equals(mid)) {
				resList.add(menu);
				selectTreeTableChildrend(resList, list, menu.getMid());
			}
		}
	}
	
	/**
	 * 保存
	 * @param menu
	 * @return
	 */
	@Transactional(rollbackFor = Exception.class)
	public Result<?> saveMenu(MenuEntity menu) {
		LambdaQueryWrapper<MenuEntity> wrapper = Wrappers.lambdaQuery();
		wrapper.eq(MenuEntity::getCode, menu.getCode());
		wrapper.ne(menu.getMid() != null, MenuEntity::getMid, menu.getMid());
		Integer exists = dao.selectCount(wrapper);
		if(exists > CommonConstant.ZERO) {
			return Result.fail("编码重复，请重新输入");
		}
		// 主页只能有一个
		if(menu.getHomeState() == CommonConstant.ONE) {
			LambdaQueryWrapper<MenuEntity> queryWrapper = Wrappers.lambdaQuery();
			queryWrapper.ne(menu.getMid() != null, MenuEntity::getMid, menu.getMid());
			queryWrapper.eq(MenuEntity::getIsProject, menu.getIsProject());
			MenuEntity m = new MenuEntity();
			m.setHomeState(CommonConstant.ZERO);
			dao.update(m, queryWrapper);
		}
		if(menu.getMid() == null) {
			int count = dao.insert(menu);
			return count > 0 ? Result.success(Result.ADD_MSG):Result.fail(Result.ADD_FAIL_MSG);
		}else {
			int count = dao.updateById(menu);
			return count > 0 ? Result.success(Result.UPDATE_MSG):Result.fail(Result.UPDATE_FAIL_MSG);
		}
	}
	
	/**
	 * 删除
	 * @return
	 */
	@Transactional(rollbackFor = Exception.class)
	public Result<?> delete(Integer mid) {
		int count = dao.deleteById(mid);
		return count > 0 ? Result.success(Result.DELETE_MSG):Result.fail(Result.DELETE_FAIL_MSG);
	}
	
	/**
	 * 更改状态
	 * @return
	 */
	@Transactional(rollbackFor = Exception.class)
	public Result<?> updateState(MenuEntity entity) {
		int count = dao.updateById(entity);
		return count > 0 ? Result.success():Result.fail();
	}
	
	/**
	 * 获取左侧菜单
	 * @param rid
	 * @return
	 */
	public Result<?> selectTree(Integer rid) {
		MenuEntityReq menuEntityReq = new MenuEntityReq();
		menuEntityReq.setRid(rid);
		menuEntityReq.setState(CommonConstant.ONE);
		menuEntityReq.setDelFlag(CommonConstant.ZERO);
		List<MenuEntityResp> list = dao.selectTree(menuEntityReq);
 		List<MenuEntityResp> resList = selectTreeChildren(list, 0);
		return Result.success(resList);
	}
	
	public List<MenuEntityResp> selectTreeChildren(List<MenuEntityResp> list, Integer mid) {
		List<MenuEntityResp> resList = CollUtil.newArrayList();
		if(CollUtil.isNotEmpty(list)) {
			for(MenuEntityResp menu : list) {
				if(menu.getParentId().equals(mid)) {
					List<MenuEntityResp> child = selectTreeChildren(list, menu.getMid());
					menu.setChildren(child);
					resList.add(menu);
				}
			}
		}
		return resList;
	}


	/**
	 * 获取左侧菜单-All
	 * @return
	 */
	public Result<?> selectTreeAll() {
		MenuEntity menuEntity = new MenuEntity();
		menuEntity.setDelFlag(CommonConstant.ZERO);
		List<MenuEntityResp> list = dao.selectTreeAll(menuEntity);
		ArrayList<TreeResp> newList = CollUtil.newArrayList();
		for(MenuEntityResp menu : list) {
			if(menu.getParentId().equals(CommonConstant.ZERO)) {
				List<TreeResp> child = selectTreeChildrendAll(list, menu.getMid());
				newList.add(new TreeResp(menu.getMid(), CollUtil.isNotEmpty(child)?child:null, menu.getMname(), true, menu.getMname(), null, null, false, true));
			}
		}
		ArrayList<TreeResp> tempList = CollUtil.newArrayList();
		tempList.add(new TreeResp(0, newList, "默认一级", true, "默认一级", null, null, false, true));
		return Result.success(tempList);
	}
	
	public List<TreeResp> selectTreeChildrendAll(List<MenuEntityResp> list, Integer mid) {
		List<TreeResp> newList = CollUtil.newArrayList();
		if(CollUtil.isNotEmpty(list)) {
			for(MenuEntityResp menu : list) {
				if(menu.getParentId().equals(mid)) {
					List<TreeResp> child = selectTreeChildrendAll(list, menu.getMid());
					newList.add(new TreeResp(menu.getMid(), CollUtil.isNotEmpty(child)?child:null, menu.getMname(), true, menu.getMname(), null, null, false, true));
				}
			}
		}
		return newList;
	}

	/**
	 * 菜单选择角色
	 * @return
	 */
	@Override
	public Result<?> selectMenuRole(String mid) {
		List<RoleDtoResp> list = dao.selectMenuRole(mid);
		return Result.page(list, Long.valueOf(list.size()));
	}

	/**
	 * 保存菜单选择角色
	 * @return
	 */
	@Override
	public Result<?> saveMenuRole(String[] rids, Integer mid, Integer lastOid) {
		dao.deleteRoleMenu(new RoleMenuEntity(null, null, mid));
		if(ArrayUtil.isNotEmpty(rids)) {
			List<RoleMenuEntity> list = CollUtil.newArrayList();
			for(String rid : rids) {
				list.add(new RoleMenuEntity(null, Integer.parseInt(rid), mid));
			}
			dao.insertRoleMenu(list);
		}
		return Result.success();
	}
	
	
	
	
}
